// row expander
var expander_content_audit = new Ext.ux.grid.RowExpander({
    tpl : new Ext.Template(
        '<p><b>考核内容:</b> {content}</p><br>',
        '<p><b>评分标准:</b> {spec}</p>'
    )
});
var cm_goaldetail_audit = new Ext.grid.ColumnModel([
	new Ext.grid.CheckboxSelectionModel(),
	expander_content_audit,
	new Ext.grid.RowNumberer({header : '序号', width : 40, dataIndex: 'id'}),
	{id: 'categoryId',header: "指标目录", width: 180, hidden: true, dataIndex: 'categoryId'},
    {id: 'categoryNamePath',header: "指标目录路径", width: 180, sortable: true, dataIndex: 'categoryNamePath'},
	{id: 'content',header: "指标考核内容", width: 200, sortable: true, dataIndex: 'content'},
	{id: 'point',header: "标准分值", width: 60, sortable: true, dataIndex: 'point'},
	{id: 'spec',header: "评分标准", width: 160, sortable: true, dataIndex: 'spec'},
	{id: 'ordering',header: "排序", width: 100, hidden : true, dataIndex: 'ordering'},
	{id: 'memo',header: "备注", width: 160, hidden : true, dataIndex: 'memo'},
	{id: 'checkOrgId',header: "考核责任单位", width: 100, sortable: true, dataIndex: 'checkOrgId',
		renderer: function(value, p, r) {
			var ret = '';
			var size = ds_org_select.getCount();
			for (var i = 0; i < size; i++) {
				var record = ds_org_select.getAt(i);
				var id = record.get('id');
				if (id == value) {
					ret = record.get('name');
					break;
				}
			}
			return (ret == '' || ret == null) ? value : ret;
		}},
	{id: 'percent',header: "换算关系(%)", width: 80, hidden: true, dataIndex: 'percent'},
    {id: 'categoryIdPath',header: "指标目录id 路径 ", width: 80, hidden : true, dataIndex: 'categoryIdPath'},
    {id: 'status',header: "状态", width: 60, dataIndex: 'status', renderer: fun_getGoalStatus},
	{id: 'year',header: "考核年度",hidden : true, width: 120, dataIndex: 'year'}
//	{
//	  header : "操作",
//	  width : 150,
//	  dataIndex : 'id',
//	  align : 'center',
//	  renderer : function(value, cellmeta, record, rowIndex, columnIndex, store) {
//			var contentId = Ext.id();
//			var audit = record.get("status") == "audit_yes";
//			var btn = createGridButton.defer(1, this, [contentId]);
//			function createGridButton() {
//				return new Ext.Button({
//							text : audit ? '查看':'审核',
//							iconCls : 'icon-edit',
////							height: 24,
//							handler : function() {
////								alert("rowIndex = " + rowIndex + "columnIndex = " + columnIndex  );
//								grid_goaldetail_audit.getSelectionModel().selectRow(rowIndex);
//								window_audit_goaldetail.show(this);
//								window_audit_goaldetail.center();
//							 	var frmCmp = Ext.getCmp("form_audit_goaldetail");
//							 	var frm = frmCmp.getForm();
//								
//								// set value
//								frm.findField('goalDetail.id').setValue(record.get("id"));
//								
//								frm.findField('goalDetail.content').setValue(record.get("content"));
//								frm.findField('goalDetail.point').setValue(record.get("point"));
//								frm.findField('goalDetail.spec').setValue(record.get("spec"));
//								frm.findField('goalDetail.ordering').setValue(record.get("ordering"));
//								frm.findField('goalDetail.memo').setValue(record.get("memo"));
//								frm.findField('goalDetail.checkOrgId').setValue(record.get("checkOrgId"));
//								frm.findField('goalDetail.percent').setValue(record.get("percent"));
//								frm.findField('goalDetail.categoryIdPath').setValue(record.get("categoryIdPath"));
//								frm.findField('goalDetail.categoryNamePath').setValue(record.get("categoryNamePath"));
//								frm.findField('goalDetail.year').setValue(record.get("year"));
//								frm.findField('goalDetail.categoryId').setValue(record.get("categoryId"));
//								try {
//									frm.findField('goalDetail.categoryId').setRawValue(record.get("categoryNamePath"));
//								}catch (e){
//									
//								}
//				
//								frm.clearInvalid();
//								var btnOk = Ext.getCmp('btn_self_audit_ok');
//								if (audit) {
//									btnOk.disable();
//								} else {
//									btnOk.enable();
//								}
//							} 
//						}).render(document.body, contentId);
//			}
//		return ('<div id="' + contentId + '"/>');
//	  }
//	}
]);
		
var window_audit_goaldetail = new Ext.Window({
			title : '指标细则审核',
			width : 480,
			height : 640,
			resizable : false,
			autoHeight : true,
			modal : true,
			closeAction : 'hide',
			listeners : {
				'hide' : function() {
					this.setTitle('指标细则审核');
					Ext.getCmp("form_audit_goaldetail").getForm().reset();
				}
			},
			items : [new Ext.FormPanel({
						id : 'form_audit_goaldetail',
						labelWidth : 100,
						labelAlign : 'right',
						url : '/supervise/biz/goaldetail/auditGoalDetail.action',
						method : 'post',
						border : false,
						baseCls : 'x-plain',
						bodyStyle : 'padding:5px 5px 0',
						defaults : {
							anchor : '90%',
							width : 240,
							msgTarget : 'side' // 验证信息显示右边
						},
						defaultType : 'textfield',
						items : [{
									xtype : 'hidden',
									name : 'goalDetail.id'
								},{
									xtype : 'combo',
									fieldLabel : '<span style="color: red">*&nbsp;</span>考核年度',
									hiddenName : 'goalDetail.year',
									valueField : 'value',
									displayField : 'text',
									value: check_year,
									mode : 'local',
									store : ds_year_select,
									value : select_year,
									selectOnFocus : true,
									editable : false,
									disabled : true,
									allowBlank : false,
									width : 80,
									typeAhead : true,
									readOnly : true,
									triggerAction : 'all',
									loadingText : '加载中...',
									emptyText : '请选择考核年度'
								}, {
									xtype : 'combo',
									fieldLabel : '指标目录',
									hiddenName : 'goalDetail.categoryId',
									valueField : 'value',
									displayField : 'text',
									mode : 'local',
									store : new Ext.data.SimpleStore({
											data:[],
											fields:["value" , "text"]
									}),
									value : '',
									selectOnFocus : true,
									editable : false,
									disabled : true,
									allowBlank : false,
									width : 80,
									typeAhead : true,
									readOnly : true,
									triggerAction : 'all',
									loadingText : '加载中...',
									emptyText : '请选择指标目录'
								}, {
									xtype : 'textarea',
									fieldLabel : '<span style="color: red">*&nbsp;</span>考核内容',
									name : 'goalDetail.content',
									height : 200,
									allowBlank : false
								},{
									xtype : 'numberfield',
									fieldLabel : '<span style="color: red">*&nbsp;</span>标准分值',
									name : 'goalDetail.point',
									readOnly : true,
									allowBlank : false,
									maxLength : 20
								},{
									xtype : 'textarea',
									fieldLabel : '<span style="color: red">*&nbsp;</span>评分标准',
									name : 'goalDetail.spec',
									allowBlank : false
								},{
									xtype : 'hidden',
//									fieldLabel : '排序',
									name : 'goalDetail.ordering',
									value : 4
								}, {
									xtype : 'combo',
									fieldLabel : '<span style="color: red">*&nbsp;</span>考核责任单位',
									hiddenName : 'goalDetail.checkOrgId',
									valueField : 'id',
									displayField : 'name',
									mode : 'remote',
									store : ds_org_select,
									selectOnFocus : true,
									readOnly : true,
									disabled : true,
									editable : false,
									allowBlank : false,
									triggerAction : 'all',
									loadingText : '加载中...',
									emptyText : '请选择部门'
								},{
									xtype : 'hidden',
									name : 'goalDetail.percent',
									value : 1
								}, {
									xtype : 'textarea',
									fieldLabel : '备注',
									name : 'goalDetail.memo'
								},{ 
									xtype : 'hidden',
//									fieldLabel : '指标目录id 路径',
									name : 'goalDetail.categoryIdPath'
								},{ 
									xtype : 'hidden',
//									fieldLabel : '考核指标目录名称路径',
									name : 'goalDetail.categoryNamePath'
								},{
									xtype : 'combo',
									fieldLabel : '状态',
									mode : 'local',
									name : 'goalDetail_status',
									hiddenName : 'goalDetail.status',
									editable : false,
									allowBlank : false,
									store : new Ext.data.SimpleStore({
										data : [['audit_yes', '审核通过'], ['audit_no', '审核不通过']],
										fields : ['value', 'text']
									}),
									displayField : 'text',
									valueField : 'value',
									mode : 'local',
									triggerAction : 'all',
									emptyText : '请选状态'
								}],
						buttonAlign : 'center',
						minButtonWidth : 60,
						buttons : [{
									id : 'btn_goaldetail_audit_ok',
									text : '确定',
									handler : function(btn) {
										var frm = Ext.getCmp("form_audit_goaldetail").getForm();
										if (frm.isValid()) {
											btn.disable();
											var cnfield = frm.findField('goalDetail.content');
											frm.submit({
														waitTitle : '请稍候',
														waitMsg : '正在提交表单数据,请稍候...',
														success : function(form, action) {
															var record = grid_goaldetail_audit.getSelectionModel().getSelected();
//															// set value
															record.set("status", frm.findField('goalDetail.status').getValue());
															record.set("memo", frm.findField('goalDetail.memo').getValue());
															record.commit();
															frm.reset();
															btn.enable();
															window_audit_goaldetail.hide();
														},
														failure : function() {
															Ext.Msg.show({
																		title : '错误提示',
																		msg : '"' + cnfield.getValue() + '" ' + '名称可能已经存在!',
																		buttons : Ext.Msg.OK,
																		fn : function() {
																			cnfield.focus(true);
																			btn.enable();
																		},
																		icon : Ext.Msg.ERROR
																	});
														}
													});
										}
									}
								}, {
									text : '取消',
									handler : function() {
										window_audit_goaldetail.hide();
									}
								}]
					})]
		});
var btn_goaldetail_audit_yes = new Ext.Button({
	text : '审核通过',
	iconCls : 'icon-add',
	handler : function() {		if(!grid_goaldetail_audit.checkMany()){
			return;
		}
		var records = grid_goaldetail_audit.getSelectionModel().getSelections();
		var ids = [];
		for(var i = 0, count = records.length; i < count; i++){
			ids.push(records[i].get('id'));
		}
		Ext.Msg.confirm('确认审核通过', '你确定审核通过这些指标?', function(btn) {
			if (btn != 'yes') {
				return;
			}
		});
		//		提交保存数据
		Ext.getBody().mask("数据正在提交，请稍等...","x-mask-loading"); 
		Ext.Ajax.request({
			url : '/supervise/biz/goaldetail/auditYes.action',
			success : function(response, options) {
				Ext.getBody().unmask();
				grid_goaldetail_audit.getStore().reload();
				Ext.Msg.alert('提示', '成功审核通过！');
			 
			},
			failure : function() {
				Ext.getBody().unmask();
				Ext.Msg.alert('提示', '数据保存失败！');
			},
			params : {
				ids : ids.join(',')
			}
		});
	}
});
var btn_goaldetail_audit_no = new Ext.Button({
	text : '审核不通过',
	iconCls : 'icon-del',
	handler : function() {
		if(!grid_goaldetail_audit.checkMany()){
			return;
		}
		var records = grid_goaldetail_audit.getSelectionModel().getSelections();
		var ids = [];
		for(var i = 0, count = records.length; i < count; i++){
			ids.push(records[i].get('id'));
		}
		Ext.Msg.confirm('确认审核不通过', '你确定审核不通过这些指标?', function(btn) {
					if (btn != 'yes') {
						return;
					}
				});
		//		提交保存数据
		Ext.getBody().mask("数据正在提交，请稍等...","x-mask-loading"); 
		Ext.Ajax.request({
			url : '/supervise/biz/goaldetail/auditNo.action',
			success : function(response, options) {
				Ext.getBody().unmask();
				grid_goaldetail_audit.getStore().reload();
				Ext.Msg.alert('提示', '成功审核不通过！');
			 
			},
			failure : function() {
				Ext.getBody().unmask();
				Ext.Msg.alert('提示', '数据保存失败！');
			},
			params : {
				ids : ids.join(',')
			}
		});
	}
});
var btn_goaldetail_audit = new Ext.Button({
			text : '审核',
			iconCls : 'icon-edit',
			handler : function() {
				if (!grid_goaldetail_audit.checkOne()) {
					return;
				}

				var record = grid_goaldetail_audit.getSelectionModel().getSelected();
				window_audit_goaldetail.show(this);
				window_audit_goaldetail.center();
				var frmCmp = Ext.getCmp("form_audit_goaldetail");
				var frm = frmCmp.getForm();
				// set value
				frm.findField('goalDetail.id').setValue(record.get("id"));

				frm.findField('goalDetail.content').setValue(record
						.get("content"));
				frm.findField('goalDetail.point').setValue(record.get("point"));
				frm.findField('goalDetail.spec').setValue(record.get("spec"));
				frm.findField('goalDetail.ordering').setValue(record
						.get("ordering"));
				frm.findField('goalDetail.memo').setValue(record.get("memo"));
				frm.findField('goalDetail.checkOrgId').setValue(record
						.get("checkOrgId"));
				frm.findField('goalDetail.percent').setValue(record
						.get("percent"));
				frm.findField('goalDetail.categoryIdPath').setValue(record
						.get("categoryIdPath"));
				frm.findField('goalDetail.categoryNamePath').setValue(record
						.get("categoryNamePath"));
				frm.findField('goalDetail.year').setValue(record.get("year"));
				frm.findField('goalDetail.categoryId').setValue(record
						.get("categoryId"));
				try {
					frm.findField('goalDetail.categoryId').setRawValue(record
							.get("categoryNamePath"));
				} catch (e) {

				}

				frm.clearInvalid();
			}
		});
		
var btn_del_goaldetail_audit = new Ext.Button({
	text : '删除',
	iconCls : 'icon-del',
	handler : function() {
		if (!grid_goaldetail_audit.checkOne()){
			return;
		}
		var record = grid_goaldetail_audit.getSelectionModel().getSelected();
		var status = record.get("status");
		if(status=='audit_yes'){
			alert("此指标已经审核通过，不能删除！");
			return;
		}
		if (record) {
			Ext.Msg.confirm('确认删除', '你确定删除该条记录?', function(btn) {
						if (btn == 'yes') {
							Ext.Ajax.request({
										url : '/supervise/biz/goaldetail/deleteGoalDetail.action',
										params : {
											id : record.data.id
										},
										success : function() {
											grid_goaldetail_audit.getStore().remove(record);
										},
										failure : function() {
											Ext.Msg.show({
														title : '错误提示',
														msg : '删除时发生错误!',
														buttons : Ext.Msg.OK,
														icon : Ext.Msg.ERROR
													});
										}
									});
						}
					});
		}
	}
});			
var ds_goaldetail_audit = new Ext.data.Store({
	proxy : new Ext.data.HttpProxy({
		url : '/supervise/biz/goaldetail/findGoalDetailAuditByPage.action'
	}),
	reader : new Ext.data.JsonReader({
			totalProperty : 'totalProperty',
			root : 'root'
		}, [{
			name : 'id',
			type : 'int'
		}, {
			name : 'categoryId',
			type : 'int'
		},{
			name : 'content',
			type : 'string'
		},{
			name : 'point',
			type : 'float'
		},{
			name : 'spec',
			type : 'string'
		}, {
			name : 'ordering',
			type : 'float'
		}, {
			name : 'memo',
			type : 'string'
		},{
			name : 'checkOrgId',
			type : 'int'
		},{
			name : 'percent',
			type : 'float'
		},{
			name : 'categoryIdPath',
			type : 'string'
		},{
			name : 'categoryNamePath',
			type : 'string'
		},{
			name : 'status',
			type : 'string'
		},{
		name : 'year',
		type : 'int'
	}])
});

var grid_goaldetail_audit = new Ext.grid.GridPanel({
	iconCls : 'icon-grid',
	loadMask : {
		msg : '数据加载中...'
	},
	viewConfig : {
		forceFit : true
	},
	region : 'center',
	cm : cm_goaldetail_audit,
	sm : new Ext.grid.CheckboxSelectionModel({singleSelect : false}),
	store : ds_goaldetail_audit,
	autoExpandColumn : 'content',
	plugins: expander_content_audit,
	tbar : [btn_goaldetail_audit_yes, '-', btn_goaldetail_audit_no, '-', btn_goaldetail_audit,'-', btn_del_goaldetail_audit],
	bbar : new Ext.PagingToolbar({
				pageSize : 20,
				store : ds_goaldetail_audit,
				displayInfo : true,
				displayMsg : '第 {0} - {1} 条  共 {2} 条',
				refreshText : "刷新",
				emptyMsg : "没有记录"
			}),
	// 检测至少选择一个
	checkOne : function() {
		var selections = this.getSelectionModel().getSelections();
		if (selections.length == 0) {
			Ext.MessageBox.alert("提示", "请选择一条的记录！");
			return false;
		} else if (selections.length != 1) {
			Ext.MessageBox.alert("提示", "不能选择多行！");
			return false;
		}
		return true;
	},

	// 检测必须选择一个
	checkMany : function() {
		var selections = this.getSelectionModel().getSelections();
		if (selections.length == 0) {
			Ext.MessageBox.alert("提示", "请至少选择一条的记录！");
			return false;
		}
		return true;
//	},
//	listeners : {
//		'render' : function(e) {
//		ds_goaldetail_audit.baseParams = {
//					year : new Date().getFullYear()
//				};
//			ds_goaldetail_audit.load({params : {
//					start : 0,
//					limit : 20
//				}});
//		}
	}

});

var qpanel_goaldetail_audit = new Ext.Panel({
	height : 160,
	region : "north",
	baseCls:"x-plain",
	style:"padding:5px",
	layout:"column",
	items:[{
		columnWidth:0.6,
		layout:"form",
		frame : true,
		baseCls : 'x-plain',
		items : [new Ext.FormPanel({
			id: 'form_query_goaldetail_audit',
			labelAlign : 'right',
			border : false,
			baseCls : 'x-plain',
			bodyStyle : 'padding:5px 5px 0',
			defaults : {
				anchor : '90%',
				width : 240,
				msgTarget : 'side' // 验证信息显示右边
			},
			defaultType : 'textfield',
			items:[{
					xtype : 'combo',
					fieldLabel : '<span style="color: red">*&nbsp;</span>考核年度',
					hiddenName : 'year',
					valueField : 'value',
					displayField : 'text',
					value: check_year,
					mode : 'local',
					store : ds_year_select,
//					value : select_year,
					selectOnFocus : true,
					editable : false,
					allowBlank : false,
					typeAhead : true,
					readOnly : true,
					triggerAction : 'all',
					loadingText : '加载中...',
					emptyText : '请选择考核年度',
					listeners : {
						'select' : function(combo, record, index) {
							select_year = combo.getValue();
							var combotree = Ext.getCmp("combotree_query_aduit");
						 	combotree.clearValue();
 							try{
	 							var root = combotree.tree.getRootNode();
	 							if(root){
	 								root.reload();
	 							}
 							}catch(e){}
						}
					}
				},{
					id : 'combotree_query_aduit',
					xtype : 'combotree',
					fieldLabel : '指标目录',
					hiddenName : 'goalDetail.categoryId',
					selectNodeModel:'leaf', //只有选叶子时，才设置值  
					allowBlank : false,
					tree : {
						xtype:'treepanel',
						rootVisible : false,
						autoScroll : true,
						firstLoad : true,
						loadingText : '加载中...',
						loader : new Ext.tree.TreeLoader(),
						root : new Ext.tree.AsyncTreeNode(),
						listeners : {
							'beforeload' : function(node) {
									var checkYear = select_year;
									var nodeId = Ext.num(node.id, null);
									if (Ext.isNumber(nodeId)) {
										this.loader.dataUrl = '/supervise/biz/goalcategory/getChildrenById.action?checkYear='
												+ checkYear + '&nodeId=' + node.id;
									} else {
										this.loader.dataUrl = "/supervise/biz/goalcategory/getRoot.action?checkYear=" + checkYear;
									}
								}
							}
				    	},
				    	listeners:{  
				            beforeselect: function(comboxtree,newNode,oldNode){//选择树结点设值之前的事件  
			            },  
			            select: function(comboxtree,newNode,oldNode){//选择树结点设值之后的事件  
			            	var frm = Ext.getCmp("form_query_goaldetail_audit").getForm();
							frm.findField('categoryId').setValue(newNode.id);
			            },  
			            afterchange: function(comboxtree,newNode,oldNode){//选择树结点设值之后，并当新值和旧值不相等时的事件  
			            }  
			     	}  
				},{
					xtype : 'hidden',
					name : 'categoryId'
				}, {
					xtype : 'combo',
					fieldLabel : '指标状态',
					mode : 'local',
					name : 'goal_status',
					hiddenName : 'status',
					editable : false,
					allowBlank : false,
					store : new Ext.data.SimpleStore({
							data : data_goal_status,
							fields : ['text', 'value']
						}),
					displayField : 'text',
					valueField : 'value',
					mode : 'local',
					triggerAction : 'all',
					emptyText : '请选择指标状态'
				}, {
					xtype : 'combo',
					fieldLabel : '申报单位',
					hiddenName : 'applyOrgId',
					valueField : 'id',
					displayField : 'name',
					mode : 'remote',
					store : ds_org_select,
	//						anchor : '100%',
					selectOnFocus : true,
					editable : false,
					allowBlank : true,
					triggerAction : 'all',
					loadingText : '加载中...',
					emptyText : '请选择申报单位'
				}],
			buttonAlign : 'center',
			minButtonWidth : 60,
			buttons : [{
						text : '查询',
						handler : function(btn) {
							var frm = btn.ownerCt.ownerCt.getForm();
							ds_goaldetail_audit.baseParams = {
								year : frm.findField('year').getValue(),
								categoryId : frm.findField('categoryId').getValue(),
								status : frm.findField('status').getValue(),
								applyOrgId :frm.findField('applyOrgId').getValue()
							};
							ds_goaldetail_audit.load({params : {
								start : 0,limit : 20
							}});}
					},{
						text : '重置',
						handler : function() { 
							var frm = Ext.getCmp('form_query_goaldetail_audit').getForm();
							frm.reset();
							frm.findField('goalDetail.categoryId').setRawValue("");
						}
					}]
		})]
	}]
});

var query_goaldetail_audit =  new Ext.Panel({
	frame : false,
	region : 'center',
	labelWidth : 65,
	title : '指标细则审核',
	labelPad : 45,
	buttonAlign : 'center',
	layout : 'border',
	items : [qpanel_goaldetail_audit, grid_goaldetail_audit] //, 
});	
var p_goaldetailaudit = {
	id : 'goaldetailaudit-panel',
	border : false,
	layout : 'border',
	items : [query_goaldetail_audit]
}; 